<template>
    <view>
      <uni-popup ref="popup" :is-mask-click="false" :animation="true" type="bottom" id="toast" :safe-area="false" style="z-index: 9999;">
        <view class="popup-content">
            <view class="title">
              <view class="left">
                <image class="left1" v-show="showlogin==2" @tap="toshowone" src="../../static/images/xiangzuop.png"></image>
              </view>
              <view class="text">{{ showlogin ==1?'Log in or create an account':'Email login' }}</view>
              <image class="close" src="../../static/images/close.png" @tap="close"></image>
            </view>
            <view  v-show="showlogin==2">
              <input class="inputemail" v-model="emailValue" placeholder="Fill in your email address">
              <view class="Verification">
                <input class="code" v-model="emailcode" placeholder="Fill in the verification code">
                <view class="clickget" v-show="showcodebuttom == 0" @tap="getcode">Get Code</view>
                <view class="Countdown" v-show="showcodebuttom == 1">{{timevalue}}S</view>
              </view>
              <view class="submit" @tap="submit">Login or Register</view>
              <!-- <view class="title2">Other login methods</view>
              <view class="imgs">
                <image class="imgitem" @tap="tofacebook" src="../../static/images/facebook.png"></image>
                <image class="imgitem" @tap="togoogle" src="../../static/images/google.png"></image>
              </view> -->
          </view>
          <view v-show="showlogin==1">
            <view class="loginbuttom1" @tap="toshowtwo" style="margin-top: 60rpx;">
              <image class="img1" src="../../static/images/youxiang.png"></image>
              <text class="text">Sign in with Email</text>
            </view>
            <view class="loginbuttom1" @tap="togoogle" style="border: 2rpx solid rgba(56, 56, 56, 1);">
              <image class="img1" style="width: 80rpx;height: 80rpx;margin-top: 10rpx;" src="../../static/images/yuangoogle.png"></image>
              <text class="text" style="color: rgba(0, 0, 0, 1);">Sign in with Google</text>
            </view>
            <view class="loginbuttom1" @tap="tofacebook" style="border: 2rpx solid rgba(24, 119, 242, 1);">
              <image class="img1" style="width: 80rpx;height: 80rpx;margin-top: 10rpx;" src="../../static/images/yuanface.png"></image>
              <text class="text" style="color: rgba(24, 119, 242, 1);">Sign in with Facebook</text>
            </view>
          </view>
        </view>
      </uni-popup>
    </view>
  </template>
  
  <script>
  
  import { getrequest, postrequest,EventStatistics } from '../../util/api'

  export default {

    data() {
			return {
        showlogin:1,  //登录弹框显示那个
        istologin:false,// 判断是否点击登录的参数
        href:'', //首页地址
				channelNo:'',
				triggered: false,  //下拉加载控制变量
				lists:[],// 首页的列表
				liststotal:'', //视频总数
				page:1, // 请求视频的页数
        emailValue:'', //邮箱18581343206@163.com
        emailcode:'', // 邮箱验证码
        userId:'', //用户id
        showcodebuttom:0, //点击获取验证码倒计时
        timevalue:60,
        channel_no:'',
			} 
		},
    props: {     

    },
    // 组件实例已经创建完成，属性已经绑定，但尚未替换真实的DOM之前触发。
    created(){
			console.log('created')
			const oScript = document.createElement('script');
			oScript.src = 'https://accounts.google.com/gsi/client?hl=en';
			document.body.appendChild(oScript);
			// 添加sdk
			if (!window.FB) {
				window.fbAsyncInit = function() {
					FB.init({
						appId: '438090762320756', // 填入自己 app 的 id
						cookie: true,
						xfbml: true,
						version: 'v17.0' // 目前版本
					})
				};
				(function(d, s, id) {
					var js,
						fjs = d.getElementsByTagName(s)[0]
					if (d.getElementById(id)) {
						return
					}
					js = d.createElement(s)
					js.id = id
					js.src = 'https://connect.facebook.net/en_US/sdk.js'
					fjs.parentNode.insertBefore(js, fjs)
				})(document, 'script', 'facebook-jssdk')
			}
		},
    // 组件挂载开始之前执行。
    beforeMount(){

    },
    mounted(){
      this.channel_no = uni.getStorageSync('channel_no') || ''
      this.href = uni.getStorageSync('href') || ''
      console.log('this.href',this.href)
            // 事件统计
      EventStatistics('登录验证','登录弹框')
    },
    methods: {
      // 跳转到facebook登录
      async tofacebook(){
        const that = this
        if(this.istologin){
          uni.showToast({
            title:'Ready to jump',
            icon:'none',
            duration: 1500,
            // position: 'top', 
          })
          return
        }
        this.istologin = true

				// 检查登录状态
				FB.getLoginStatus(function(response) {
					console.log("已登录：",response)
					// 登录状态 - 已登录
					if (response.status === 'connected') {
						// 用户已登录，调用 Graph API 获取用户资料
						// FB.api('/me', {
						// 	fields: 'id,name,email'
						// }, function(apiResponse) {
						// 	if (apiResponse && !apiResponse.error) {
						// 		// 成功获取用户资料
						// 		console.log('用户资料:', apiResponse);
						// 		// 在这里可以将用户资料发送到后端服务器进行处理和存储
						// 	} else {
						// 		// 获取用户资料失败
						// 		console.error('获取用户资料失败:', apiResponse.error);
						// 	}
						// });

            // 调用三方登录接口1
            if(response.authResponse){
              that.facebooksf(response.authResponse)
            }else{
              that.istologin = false
              return
            }

					} else {
						// 登录状态 - 未登录
						FB.login(
							function(response) {
								console.log("登录", response)
                  // 调用三方登录接口1
                  if(response.authResponse){
                    that.facebooksf(response.authResponse)
                  }else{
                    // that.funistologin()
                    that.istologin = false
                    return
                  }
								// 获取用户资料
								// 用户已登录，调用 Graph API 获取用户资料
								// FB.api('/me', {
								// 	fields: 'id,name,email'
								// }, function(apiResponse) {
								// 	if (apiResponse && !apiResponse.error) {
								// 		// 成功获取用户资料
								// 		console.log('用户资料:', apiResponse);
								// 		// 在这里可以将用户资料发送到后端服务器进行处理和存储
								// 	} else {
								// 		// 获取用户资料失败
								// 		console.error('获取用户资料失败:', apiResponse.error);
								// 	}
								// });
							},

							// 授权的各种权限
							//[facebook权限参考文档](https://developers.facebook.com/docs/permissions/reference)
							{
								scope: 'email,public_profile'
							}
						)
					}
				})
      },
      funistologin(){
        this.istologin = true
      },
      // fackbook三方接口
      async facebooksf(response){
        // console.log('response',response)
        // alert('response',response)
        if(!response||!response.accessToken){
          this.istologin = false
          return
        }
        let params = {
					access_token: response.accessToken,
          // encodeURIComponent(this.href),
				}
        const res = await postrequest('/facebook/login',params)
        console.log('res',res)
        if(res.code == 200){
          this.istologin = false
          uni.showToast({
            title:'jumping...',
            icon:'none',
            duration: 1500,
            // position: 'top', 
          })
          // window.location.replace(res.data);
          // window.open(res.data, '_blank');
          // window.location.href = res.data
          uni.setStorageSync('token', res.data.token);
            // 页面刷新
            window.location.reload();
        }else{
          this.istologin = false
          uni.showToast({
            title:'Authorization failure',
            icon:'none',
            duration: 1500,
            // position: 'top', 
          })
        }
      },
      // 退出facebook静谧登录
      facebookout(){
				FB.getLoginStatus(function(response) {
					// 检查登录状态
					if (response.status === 'connected') {
						FB.api('/me/permissions', 'DELETE', function(res) {
							FB.logout()
							alert('退出成功！')
						})
					} else {
						alert('暂未登录无需退出！')

					}
				})
      },
      // 跳转到的谷歌登录
      async togoogle(){
        if(this.istologin){
          uni.showToast({
            title:'Ready to jump',
            icon:'none',
            duration: 1500,
            // position: 'top', 
          })
          return
        }
        this.istologin = true
        let params = {
					state:this.href,
				}
        const res = await getrequest('/google/googleUrl',params)
        console.log('res',res)
        if(res.code == 200){
          this.istologin = false
          uni.showToast({
            title:'jumping...',
            icon:'none',
            duration: 1500,
            // position: 'top', 
          })
          window.location.href = res.data
        }else{
          this.istologin = false
          uni.showToast({
            title:'Authorization failure',
            icon:'none',
            duration: 1500,
            position: 'top', 
          })
        }
      },
       // 打开弹框
      open() {
        this.$refs.popup.open()
      },
      // 关闭弹框
      close() {
        this.$refs.popup.close()
      },
      // 获取验证码
      async getcode(){
        // 邮箱进行验证
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!this.emailValue.match(emailRegex)) {
          uni.showToast({
            title:'Fill in the correct email address',
            duration: 1500,
            icon:'none',
            position: 'top', 
          })
          return
        }
          // 请求倒计时 部分
          this.showcodebuttom = 1
          console.log('aa',this.showcodebuttom)
          setInterval(()=>{
            if(this.timevalue >= 1){
              this.timevalue --
            }else{
              this.timevalue = 60
              this.showcodebuttom = 0
            }
          },1000)

        // 请求code验证码
				let params = {
					email:this.emailValue,
          channel_no: this.channel_no,
				}
        const res = await getrequest('/api/user/get_code',params)
        console.log('res',res)
        if(res.code == 200){
          uni.showToast({
            title:'The email verification was successful. Procedure',
            duration: 1500,
            icon:'none',
            position: 'top', 
          })
        }else{
          uni.showToast({
            title:'Acquisition failure',
            duration: 1500,
            icon:'none',
            position: 'top', 
          })
        }
      },
      // 登录/注册
      async submit(){
        // alert("这是一个警告消息！");
        if(this.emailValue==''||this.emailcode==''){
          return uni.showToast({
            title:'Please fill in the information',
            icon:'none',
            duration: 2000,
          })
        }
        let params = {
					email:this.emailValue,
          code:this.emailcode,
				}
        const res = await postrequest('/api/user/login',params)
        console.log('res',res)
        if(res.code == 200){
          this.userId = res.data.user_id
          uni.setStorageSync('user_id', res.data.user_id); 
          uni.setStorageSync('token', res.data.token);
          uni.setStorageSync('email', this.emailValue);

          // 先关闭弹框
          this.close()
          // 调用用户查询接口
          // this.$emit('getuserDetail'); // 触发自定义事件
          this.getUserDetail && this.getUserDetail()
          // 页面刷新
          window.location.reload();
        }else{
          uni.showToast({
            title:'The email address or verification code is incorrect, please fill in again',
            duration: 1500,
            icon:'none',
            position: 'top', 
          })
        }
      },
      // 点击切换邮箱登录
      toshowtwo(){
        this.showlogin = 2
      },
      // 邮箱登录返回上一级别
      toshowone(){
        this.showlogin = 1
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .popup-content {
    width: 750rpx;
    height: 620rpx;
    border-radius: 20rpx 20rpx 0 0;
    font-family: '思源黑体';
    z-index: 100;
    // margin-bottom: 100rpx;
    background: linear-gradient(180deg, rgba(255, 243, 240, 1) 0%, rgba(255, 255, 255, 1) 100%);
    .title{
      width: 750rpx;
      padding-top: 30rpx;
      height: 40rpx;
      display: flex;
      .left{
        width: 50rpx;
        height: 50rpx;
        margin: -4rpx 0 0 20rpx;
        .left1{
          width: 50rpx;
          height: 50rpx;
        }
      }
      .text{
        width: 550rpx;
        height: 40rpx;
        // border: 1px solid black;
        font-size: 18px;
        line-height: 40rpx;
        color: rgba(0, 0, 0, 1);
        text-align: center;
        margin: 0 0 0 10rpx;
      }
      .close{
        width: 34rpx;
        height:34rpx;
        margin: 4rpx 0 0 50rpx;
      }
    }
    .inputemail{
      width: 660rpx;
      height: 80rpx;
      padding: 10rpx 20rpx;
      border: 1px solid rgba(166, 166, 166, 1);
      border-radius: 10rpx;
      margin: 0 auto;
      margin-top: 70rpx;
    }
    .Verification{
      width: 700rpx;
      height: 100rpx;
      margin: 0 auto;
      margin-top: 40rpx;
      border: 1px solid rgba(166, 166, 166, 1);
      border-radius: 10rpx;
      display: flex;
      .code{
        width: 420rpx;
        height: 80rpx;
        padding: 10rpx 20rpx;
      }
      .clickget{
        width: 240rpx;
        height: 60rpx;
        border-left: 1px solid rgba(128, 128, 128, 1);
        margin-top: 20rpx;
        font-size: 32rpx;
        line-height: 60rpx;
        color: rgba(232, 94, 63, 1);
        text-align: center;
      }
      .Countdown{
        width: 200rpx;
        height: 60rpx;
        border: 1px solid rgba(128, 128, 128, 1);
        margin-top: 20rpx;
        font-size: 32rpx;
        line-height: 60rpx;
        background-color: rgb(208, 208, 208);
        color: rgba(96, 58, 245, 1);
        border-radius: 10rpx;
        text-align: center;
      }
    }
    .submit{
      width: 660rpx;
      height: 100rpx;
      border-radius: 30px;
      background: rgba(232, 94, 63, 1);
      margin: 0 auto;
      margin-top: 80rpx;
      font-size: 32rpx;
      font-weight: 700;
      line-height: 100rpx;
      color: rgba(255, 255, 255, 1);
      text-align: center;
    }
    .title2{
      width: 700rpx;
      height: 50rpx;
      font-size: 32rpx;
      font-weight: 700;
      line-height: 50rpx;
      color: rgba(44, 44, 44, 1);
      text-align: left;
      margin: 30rpx 0 0 30rpx;
    }
    .imgs{
      width: 700rpx;
      height: 110rpx;
      // border: 1px solid black;
      margin: 20rpx;
      display: flex;
      .imgitem{
        width: 90rpx;
        height: 90rpx;
        // border: 1px solid black;
        margin: 10rpx;
      }
    }
    .loginbuttom1{
      width: 660rpx;
      height: 100rpx;
      border-radius: 30px;
      border: 2rpx solid rgba(232, 94, 63, 1);
      margin: 0 auto;
      margin-top: 40rpx;
      display: flex;
      justify-content: center;
      .img1{
        width: 80rpx;
        height: 60rpx;
        margin: 20rpx 0 0 0;
      }
      .text{
        width: 350rpx;
        height: 100rpx;
        font-size: 32rpx;
        font-weight: 700;
        line-height: 100rpx;
        color: rgba(232, 94, 63, 1);
        margin-left: 20rpx;
      }

    }

  }
	// ::v-deep .uni-sample-toast{
  //     z-index: 99999 !important;
  //     // uni-toast
  //   }

  </style>
  